import React, { Component } from 'react'
import { load, load_page } from './reducer'
import { connect } from 'react-redux'
import SimplePageComponent from '../../components/SimplePageComponent'
import { loadPost } from './actions';

class PostList extends Component {

  renderPost (item) {
    return (
      <div key={item._id}> 
        {item.title} 
      </div>
    )
  }

  render() {

    const {loaded, loading, pages, page, items, onloadPost} = this.props;

    return (

      <div>

        <div className = 'row'>
          <div className="col-lg-12">
            <div className = 'page-header'>
              <h3>Container: PostList ( This Component Will Show the Posts )</h3>
            </div>
          </div>
        </div>

        <div className = 'row'>

          <div className="col-lg-12">

            <h2>
              {loaded && <div className = 'label label-success'>Posts Loaded.</div>}
            </h2>

            <h2>
              {!loaded && !loading &&  <div className = 'label label-warning'>Posts Not Loaded. Click the Arrow of Pagination to Load Data.</div>}
            </h2>

            <h2>
              {loading && <div className = 'label label-info'>Posts Loading (takes 1 second)</div>}
            </h2>


          </div>

        </div>

        <br/>

        <button className='btn btn-primary'
                  onClick={onloadPost}>
        Click Me to Load Posts</button>


        <div> {items.map(this.renderPost)} </div>


        <SimplePageComponent
          toPageFromParent = {this.props.onloadPost}
          pages = {pages}
          page = {page} /> 

      </div>

      
    )
  }
}

function mapStateToProps(state, ownProps) {
  const {
    post: { loaded, loading, pages, page, items },
  } = state

  return {
    loaded,
    loading,
    pages,
    page,
    items,
  }
}


function mapDispatchToProps(dispatch) {
  return {
    onloadPost: (e, page_number) => {e.preventDefault();dispatch(loadPost(page_number))},
    dispatch,
  };
}

// ES6 export does not work with Webpack Chunk Splitting.
// export default connect(mapStateToProps, mapDispatchToProps)(PostList) 
module.exports = connect(mapStateToProps, mapDispatchToProps)(PostList)